
/**************************************************************

	Script		: Windows
	Version		: 1.1
	Authors		: Samuel Birch
	Desc		: 

**************************************************************/

var Windows = new Class({
	
	getOptions: function(){
		return {
			handle: 'handle',
			OnDrop: Class.empty,
			containerBorder: 0
		};
	},

	initialize: function(wins, containers, options){
		this.setOptions(this.getOptions(), options);
		
		this.wins = $$(wins);
		this.containers = $$(containers);
		this.border = this.options.containerBorder*2;
		
		this.wins.each(function(el){
			el.addEvent('drop', function(obj){
				
			}.bind(this));
			
			el.makeDraggable({
				handle: el.getElement('.'+this.options.handle),
				droppables: this.containers,
				onComplete: function(obj){
					obj.injectBefore(obj.ghost);
					obj.ghost.remove();
					
					obj.setStyles({
						left: obj.pos.left,
						top: obj.pos.top,
						position: 'relative',
						width: obj.getParent().getStyle('width').toInt()-this.border+'px',
						zIndex: obj.pos.zIndex
					});
					this.options.OnDrop(obj);
				}.bind(this),
				onBeforeStart: function(){
					el.pos = {
						left: el.getStyle('left'),
						top: el.getStyle('top'),
						container: el.getParent(),
						zIndex: el.getStyle('zIndex')
					};
					
					el.setStyles({
						position: 'absolute',
						left: el.getCoordinates().left+'px',
						top: el.getCoordinates().top+'px',
						width: el.getCoordinates().width-this.border+'px',
						zIndex: Number(el.pos.zIndex)+1
					});
				}.bind(this),
				onStart: function(){
					
					el.ghost = el.clone();
					el.ghost.setStyles({
						position: 'relative',
						left: '0px',
						top: '0px',
						opacity: 0.5,
						zIndex: el.pos.zIndex
					});
					el.ghost.injectBefore(el);
					//
					el.injectInside(document.body);
				},
				onDrag: function(win){
					if(this.showGhost){
						var inject = true
						el.ghost.getParent().getElements('.win').each(function(e){
							if(el.getCoordinates().top < Number(e.getCoordinates().top)+(e.getStyle('height').toInt()/2) && inject){
								el.ghost.injectBefore(e);
								inject = false;
							}
						});
						if(inject){
							el.ghost.injectInside(el.ghost.getParent());
						}
					}
				}.bind(this)
			}, this);
		}, this);
		
		this.containers.each(function(el){
			
			el.addEvent('over',function(win,obj){
				win.ghost.injectInside(el);
				win.ghost.setStyles({
					width: win.ghost.getParent().getStyle('width').toInt()-this.border+'px'
				});
				this.showGhost = true;
			}.bind(this));
			
			el.addEvent('leave',function(win,obj){
				this.showGhost = false;
			}.bind(this));
			
		}, this);
		
	}
	
});
Windows.implement(new Options);
Windows.implement(new Events);


/*************************************************************/

